import { useState, useRef, useEffect } from 'react';
import { QRCode } from "antd";
import topPng from './img/top.png';

import renPng from './img/ren.png';
import JianPng from './img/jian.png';
import MyButtonSm from '@/components/MyButtonSm';
import { numberPng } from './number/numberPng';
import useCountdown from "@/hook/useCountDown";
import Process from './Process';
import { Rnd } from 'react-rnd';
// import html2canvas from "html2canvas";
import useStoreFile from '@/store/useStoreFile';
import useStorePage from '@/store/useStorePage';
import MyButton from '@/components/MyButton';
import { showSpecificCamera } from '@/utils';
import { deivceLabel } from '@/constants';
import './index.less';
import { message } from 'antd';

const ipc = window.electron;


function getRandomNumber(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

let timerPrint = null
const PhotoView = (props) => {
    const { data = {}, config = {} } = props
    const { frameImg = [], propsImg = [] } = data
    const { cameraPositon } = config
    const [kuangStatus, setKuangStatus] = useState(1); //1
    const [base64, setBase64] = useState('');      // ''
    const [num, setNum] = useState(0);
    const [btnActive, setBtnActive] = useState('1');  // '1'
    const videoRef = useRef(null);
    const [loadingScreen, setLoadingScreen] = useState(false);  //false
    const [screenPath, setScreenPath] = useState('');       // ''
    const [rndArr, setRndArr] = useState([]);
    const [isBorder, setIsBorder] = useState(true);
    const { setPage } = useStorePage()
    useEffect(() => {

        ipc.on("screen", data => {

            setScreenPath(data)
            setLoadingScreen(false)
        })
        function userMedia() {
            return navigator.getUserMedia = navigator.getUserMedia ||
                navigator.webkitGetUserMedia ||
                navigator.mozGetUserMedia ||
                navigator.msGetUserMedia || null;
        }
        if (userMedia()) {

            showSpecificCamera(deivceLabel).then(stream => {
                // console.log(stream, 'stream===');
                videoRef.current.srcObject = stream;
                setTimeout(() => {
                    if (videoRef.current) {
                        videoRef.current.play();
                    }
                    // videoRef.current.play();
                    // resetCountdown();
                }, 1000);
            })
        }
    }, []);
    // const getAiani = () => {

    //     if (!base64) {
    //         message.error('请先拍摄照片');
    //         return
    //     }
    //     setLoading(true)
    //     ipc.send("photo", {
    //         base64: base64,
    //     });
    // }
    const handleImg = () => {
        var canvas = document.querySelector("#canvas");
        const videoWidth = videoRef.current.videoWidth; // 640
        const videoHeight = videoRef.current.videoHeight; // 480
        console.log(videoWidth, 'videoWidth====');

        // const maxHeight = videoWidth / radio;
        // let width;
        // let height = width / radio;
        // if (maxHeight > videoHeight) {
        //     width = videoHeight * radio;
        //     height = videoHeight;
        // } else {
        //     width = videoWidth;
        //     height = videoWidth / radio;
        // }
        canvas.width = videoWidth
        canvas.height = videoHeight
        var buffer = canvas.getContext("2d");

        buffer.drawImage(videoRef.current, 0, 0, canvas.width, canvas.height);
        // buffer.drawImage(videoRef.current, -canvas.width, 0, width, height, -width, 0, picWidth, picHeight);
        var imgData = canvas.toDataURL("image/jpeg", 1);
        setBase64(imgData)
    };

    const { count, resetCountdown } = useCountdown(5, handleImg);

    const resetPhoto = () => {
        resetCountdown();
        setBase64('')
        // setAnimateUrl('')
        setRndArr([])
        setNum(0)
    };

    const handleKuangStatus = (num) => {
        setKuangStatus(kuangStatus + num)
    }


    const handleGetPreview = () => {
        setLoadingScreen(true)
        setTimeout(() => {
            ipc.send("screen")
        }, 100)

    }
    const handleSetBorder = () => {

        if (screenPath) {
            return
        }
        setIsBorder(true)
    }

    const handleAgein = () => {
        resetPhoto();
        setScreenPath('')
        setBtnActive('1')
        setLoadingScreen(false)
    }
    const addDaoju = (e, item) => {
        e.stopPropagation()
        setRndArr([...rndArr, { img: item, id: getRandomNumber(1, 100000) }])
        setBtnActive('1')
        handleSetBorder()
    }

    const handlePrint = () => {
        if (timerPrint) {
            clearTimeout(timerPrint)
        }
        timerPrint = setTimeout(() => {
            ipc.send("print", {
                imgUrl: screenPath,
            })
        }, 100)
    }
    const handleDelete = (index) => {

        const newArr = [...rndArr]
        newArr.splice(index, 1)
        setRndArr(newArr)
    }

    return (
        <div className="photo-view-page" onClick={() => setIsBorder(false)}>
            <div className="top">
                <img src={topPng} alt="" />
            </div>
            <div className={`photo-wrap photo-wrap${kuangStatus} ${screenPath ? 'screen-ac' : ''}`}>
                <div onClick={(e) => {
                    e.stopPropagation()
                    handleSetBorder()
                }} className={`photo`}>

                    <img className={`kuang-bg kuang-bg${kuangStatus}`} src={frameImg[kuangStatus - 1]} alt="" />


                    <div className={`video-box video-box${kuangStatus}`}>
                        <video
                            id="myvideo"
                            ref={videoRef} muted
                            style={{
                                transform: "rotateY(180deg)",
                                objectFit: 'cover',
                                objectPosition: `${-cameraPositon}px center`,
                                opacity: base64 ? 0 : 1,
                            }}
                        />
                        {
                            count ? (
                                <div className="down">
                                    <img src={numberPng[count]} alt="" />
                                </div>
                            ) : null
                        }
                        <canvas id="canvas" style={{ display: "none" }}></canvas>
                        {
                            base64 ? (
                                <img key={2} style={{
                                    transform: "rotateY(180deg)",
                                    objectPosition: `${-cameraPositon}px center`,
                                }} className='previewimg' src={base64} alt="" />
                            ) : null
                        }
                    </div>
                    {
                        <div className="rnd-wrap">
                            {
                                rndArr.map((item, index) => (
                                    <Rnd
                                        style={{
                                            ...isBorder ? { border: '1px dashed #fff' } : {}
                                        }}
                                        key={item.id}
                                        default={{
                                            x: 100, // 初始 x 坐标
                                            y: 100, // 初始 y 坐标
                                        }}
                                        disableDragging={!!screenPath}
                                        onMouseDown={() => handleSetBorder()}
                                        lockAspectRatio={true} // 锁定宽高比
                                        minWidth={50} // 最小宽度
                                        minHeight={50} // 最小高度
                                    // bounds="parent" // 限制在父元素内拖拽
                                    >
                                        <div className='rnd-item'>
                                            {isBorder ? (
                                                <span onClick={() => handleDelete(index)} onTouchStart={() => handleDelete(index)} className='delete'>X</span>
                                            ) : null}
                                            <img src={item.img} alt="" />
                                            <span className='mask-img'></span>
                                        </div>
                                    </Rnd>
                                ))
                            }
                        </div>
                    }
                </div>
            </div>
            {!screenPath && !loadingScreen && base64 && btnActive === '1' ? (
                <div className='jian'>
                    {kuangStatus === 1 ? null : (
                        <div onClick={() => handleKuangStatus(-1)}>
                            <img className='left' src={JianPng} alt="" />
                        </div>
                    )}
                    {kuangStatus === frameImg?.length ? null : (
                        <div onClick={() => handleKuangStatus(1)}>
                            <img className='right' src={JianPng} alt="" />
                        </div>
                    )}
                </div>
            ) : null}
            {
                !loadingScreen && base64 && btnActive === '2' ? (
                    <div className='mask-biao'>
                        {propsImg.map(item => (
                            <div key={item} onClick={(e) => addDaoju(e, item)}>
                                <img src={item} />
                            </div>
                        ))}
                    </div>
                ) : null
            }
            <div className='ren' style={{

                // ...loadingScreen? { display: 'none' } : {}
            }}>
                <img src={renPng} alt="" />
            </div>
            {
                !screenPath && !loadingScreen && base64 ? (
                    <div className='btn btn2'>
                        <MyButtonSm typeClass="sm" active={btnActive === '1'} onClick={() => setBtnActive('1')}>相框</MyButtonSm>
                        <MyButtonSm typeClass="sm" active={btnActive === '2'} onClick={() => setBtnActive('2')}>道具</MyButtonSm>
                        <MyButtonSm typeClass="sm" onClick={handleGetPreview}>确定</MyButtonSm>
                        <MyButtonSm typeClass="sm y" onClick={resetPhoto} >重拍</MyButtonSm>
                    </div>
                ) : null
            }
            {
                !count && !base64 && !screenPath ? (
                    <div className="btn btn3">
                        <MyButtonSm typeClass="y" onClick={resetPhoto}>点击拍照</MyButtonSm>
                        <MyButtonSm  onClick={() => { setPage('home') }} >返回首页</MyButtonSm>
                    </div>
                ) : null
            }
            {
                screenPath ? (
                    <div className="share-box">
                        <div className="top-code">
                            <div className="qrcode">
                                <QRCode
                                    size={180}
                                    value={screenPath}
                                />
                                <span className='text'>
                                    分享给朋友
                                </span>
                            </div>
                            <div className='da-yin' onClick={handlePrint}>
                                <span>打印</span>
                                <span>照片</span>
                            </div>
                            <div className='da-yin agin-btn' onClick={handleAgein}>
                                <span>再玩</span>
                                <span>一次</span>
                            </div>
                            <div className='da-yin agin-btn1' onClick={() => {
                                setPage('home')
                            }}>
                                <span>返回</span>
                                <span>首页</span>
                            </div>
                        </div>
                    </div>
                ) : null
            }
        </div>
    )
}

export default PhotoView